package com.cyanite.playlv2;

import com.cyanite.playlv2.R;
import com.cyanite.playlv2.widget.TaskCategoryAdapter;
import com.cyanite.playlv2api.types.Group;
import com.cyanite.playlv2api.types.TaskCategory;
import com.cyanite.playlv2api.types.Trip;
import com.cyanite.playlv2api.util.ConstantsUtils.TaskCategoryConsts;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.AdapterView.OnItemClickListener;

public class TaskCategoryActivity extends Activity{

    public static final String EXTRA_TRIP_PARCEL = PlayLv2.PACKAGE_NAME
        + ".TaskCategoryActivity.EXTRA_TRIP_PARCEL";

    private StateHolder mStateHolder;
	private GridView mGridView;
	private TaskCategoryAdapter mListAdapter;
	private View mViewProgressBar;

	private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            finish();
        }
    };

	public void onCreate(Bundle savedInstanceState)	{
		super.onCreate(savedInstanceState);
		registerReceiver(mLoggedOutReceiver, new IntentFilter(PlayLv2.INTENT_ACTION_LOGGED_OUT));
		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
	    setContentView(R.layout.task_category_activity);

        mStateHolder = new StateHolder();        
        if (getIntent().hasExtra(EXTRA_TRIP_PARCEL)) {
            Trip trip = getIntent().getExtras().getParcelable(EXTRA_TRIP_PARCEL);
            mStateHolder.setUserId(trip.getUserId());
            mStateHolder.setTripId(trip.getId());
            mStateHolder.setTripCategory(trip.getCategoryId());
            String process = getResources().getString(R.string.trips_process_done);
            if (trip.getProcess() != 0) {
                process = (trip.getProcess() > 0)?
                        getResources().getString(R.string.trips_process_ongoing):
                            getResources().getString(R.string.trips_process_upcoming);
            }
            setTitle(trip.getName() + "   " + process);
        }   else {
            finish();
            return;
        }
      
        mStateHolder.setIsLoggedInUser(
                mStateHolder.getUserId() == null ||
                mStateHolder.getUserId().equals(((PlayLv2) getApplication()).getUserId()));

        mViewProgressBar = findViewById(R.id.tripTaskCategoryProgress);
        mViewProgressBar.setVisibility(View.VISIBLE);

        mStateHolder.startTaskTripTaskCategories(this);

        ensureUi();
	}

	private void ensureUi() {
        mListAdapter = new TaskCategoryAdapter(this,
                                            mStateHolder.getTaskCategories(),
                                            mStateHolder.getIsLoggedInUser());
        mGridView = (GridView)findViewById(R.id.taskCategoryGrid);
        mGridView.setAdapter(mListAdapter);
        mGridView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapter, View v, int position, long arg3) {
                TaskCategory taskcategory = mStateHolder.getTaskCategory(position);
                Intent intent = null;
                switch (taskcategory.getType())   {
                    case TaskCategoryConsts.TASK_CATEGORY_TYPE_HOTEL:
                    case TaskCategoryConsts.TASK_CATEGORY_TYPE_RESTAURANT:
                    case TaskCategoryConsts.TASK_CATEGORY_TYPE_TOTAL_FEE:
                        intent = new Intent(TaskCategoryActivity.this, ShareNearActivity.class);
                        intent.putExtra(ShareNearActivity.EXTRA_USER_ID, mStateHolder.getUserId());
                        intent.putExtra(ShareNearActivity.EXTRA_TASK_CATEGORY_PARCEL, taskcategory);
                        break;
                    case TaskCategoryConsts.TASK_CATEGORY_TYPE_TRAFFIC:
                        intent = new Intent(TaskCategoryActivity.this, ShareTrafficActivity.class);
                        intent.putExtra(ShareTrafficActivity.EXTRA_USER_ID, mStateHolder.getUserId());
                        intent.putExtra(ShareTrafficActivity.EXTRA_TASK_CATEGORY_PARCEL, taskcategory);
                        break;
                    case TaskCategoryConsts.TASK_CATEGORY_TYPE_ENTERTAINMENT:
                    case TaskCategoryConsts.TASK_CATEGORY_TYPE_SHOPPING:
                    case TaskCategoryConsts.TASK_CATEGORY_TYPE_CITY:
                    case TaskCategoryConsts.TASK_CATEGORY_TYPE_SCENERY:
                    case TaskCategoryConsts.TASK_CATEGORY_TYPE_DISCOUNT:
                    case TaskCategoryConsts.TASK_CATEGORY_TYPE_PRICE:
                    case TaskCategoryConsts.TASK_CATEGORY_TYPE_PEOPLE:
                    case TaskCategoryConsts.TASK_CATEGORY_TYPE_ACTIVITY:
                    case TaskCategoryConsts.TASK_CATEGORY_TYPE_NO1:
                    case TaskCategoryConsts.TASK_CATEGORY_TYPE_TRAVEL_AGENCY:
                        intent = new Intent(TaskCategoryActivity.this, ShareCommonActivity.class);
                        intent.putExtra(ShareCommonActivity.EXTRA_USER_ID, mStateHolder.getUserId());
                        intent.putExtra(ShareCommonActivity.EXTRA_TASK_CATEGORY_PARCEL, taskcategory);
                        intent.putExtra(ShareCommonActivity.EXTRA_TRIP_CATEGORY, mStateHolder.getTripCategory());
                        break;
                    case TaskCategoryConsts.TASK_CATEGORY_TYPE_ENDPOINT:
                    case TaskCategoryConsts.TASK_CATEGORY_TYPE_STARTPOINT:
                    case TaskCategoryConsts.TASK_CATEGORY_TYPE_PHOTO:
                    case TaskCategoryConsts.TASK_CATEGORY_TYPE_TRIP_NOTE:
                    case TaskCategoryConsts.TASK_CATEGORY_TYPE_MOOD:
                    case TaskCategoryConsts.TASK_CATEGORY_TYPE_ANOTHER:
                    case TaskCategoryConsts.TASK_CATEGORY_TYPE_SPECIAL:
                        intent = new Intent(TaskCategoryActivity.this, SharePhotoActivity.class);
                        intent.putExtra(SharePhotoActivity.EXTRA_USER_ID, mStateHolder.getUserId());
                        intent.putExtra(SharePhotoActivity.EXTRA_TASK_CATEGORY_PARCEL, taskcategory);
                        break;
                    default:
                        break;
                }
                if (intent != null) {
                    startActivity(intent);
                }
            }
        });
	}

	@Override
    public void onPause() {
        super.onPause();
        if (isFinishing()) {
            mStateHolder.cancelTaskCategory();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mLoggedOutReceiver);
    }

    private void onTripTaskCategoryTaskComplete(Group<TaskCategory> taskcats, Exception ex) {
        mViewProgressBar.setVisibility(View.GONE);
        if ( taskcats != null && taskcats.size() > 0 ) {
            mStateHolder.setTaskCategories(taskcats);
            ensureUi();
        }
    }

    private static class TripTaskCategoryTask extends AsyncTask<Void, Void, Group<TaskCategory>> {

        private TaskCategoryActivity mActivity;
        private String mTripId;
        private Exception mReason;

        public TripTaskCategoryTask(TaskCategoryActivity activity, String tripId) {
            mActivity = activity;
            mTripId = tripId;
        }

        @Override
        protected void onPreExecute() {
        }

        @Override
        protected Group<TaskCategory> doInBackground(Void... params) {
            Group<TaskCategory> taskcats = null;
            try {
                taskcats = ((PlayLv2) mActivity.getApplication()).getPlayLv2Api().taskcategories(mTripId);
            } catch (Exception ex) {
                mReason = ex;
            }
            return taskcats;
        }

        @Override
        protected void onPostExecute(Group<TaskCategory> taskcats) {
            if (mActivity != null) {
                mActivity.onTripTaskCategoryTaskComplete(taskcats, mReason);
            }
        }
    }

    private static class StateHolder {

        private String mTripId;
        private int mTripCategory;
        private String mUserId;
        private Group<TaskCategory> mTaskCategories;
        private boolean mIsLoggedInUser;
        private TripTaskCategoryTask mTaskTripTaskCategory;

        public StateHolder() {
            mIsLoggedInUser = false;
            mTaskCategories = new Group<TaskCategory>();
        }

        public String getUserId()   {
            return mUserId;
        }

        public void setUserId(String userId)    {
            mUserId = userId;
        }

        public boolean getIsLoggedInUser() {
            return mIsLoggedInUser;
        }

        public void setIsLoggedInUser(boolean isLoggedInUser) {
            mIsLoggedInUser = isLoggedInUser;
        }

        public void setTripId(String id) {
            mTripId = id;
        }

        public void setTripCategory(int category) {
            mTripCategory = category;
        }

        public int getTripCategory(){
            return mTripCategory;
        }

        public Group<TaskCategory> getTaskCategories()   {
            return mTaskCategories;
        }

        public TaskCategory getTaskCategory(int position)   {
            return mTaskCategories.get(position);
        }

        public void setTaskCategories(Group<TaskCategory> taskcats) {
            mTaskCategories = taskcats;
        }

        public void startTaskTripTaskCategories(TaskCategoryActivity activity) {
            mTaskTripTaskCategory = new TripTaskCategoryTask(activity, mTripId);
            mTaskTripTaskCategory.execute();
        }

        public void cancelTaskCategory() {
            if (mTaskTripTaskCategory != null) {
                mTaskTripTaskCategory.cancel(true);
            }
        }
    }
}
